<?php
/**
 * 一些文件操作方法的封装
 * @author jiangpengfei
 * @date 2017-11-07
 */

 namespace Util;

 class FileUtil{
    
    const FILE_TYPE_EXE = 1;
    const FILE_TYPE_MIDI = 2;
    const FILE_TYPE_RAR = 3;
    const FILE_TYPE_ZIP = 4;
    const FILE_TYPE_JPG = 5;
    const FILE_TYPE_GIF = 6;
    const FILE_TYPE_BMP = 7;
    const FILE_TYPE_PNG = 8;
    const FILE_TYPE_UNKNOWN = -1;

    /**
     * 获取文件类型
     * @param $filePath 文件路径
     * @return int 文件类型
     */
    public static function getFileType(string $filePath):int{
        $file = fopen($filePath, "rb");  
        $bin = fread($file, 2); //只读2字节  
        fclose($file);  
        $strInfo = @unpack("C2chars", $bin);  
        $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);  
        $fileType = '';  

        switch ($typeCode)  
        {  
            case 7790:  
                $fileType = self::FILE_TYPE_EXE;  
                break;  
            case 7784:  
                $fileType = self::FILE_TYPE_MIDI;  
                break;  
            case 8297:  
                $fileType = self::FILE_TYPE_RAR;  
                break;          
            case 8075:  
                $fileType = self::FILE_TYPE_ZIP;  
                break;  
            case 255216:  
                $fileType = self::FILE_TYPE_JPG;  
                break;  
            case 7173:  
                $fileType = self::FILE_TYPE_GIF;  
                break;  
            case 6677:  
                $fileType = self::FILE_TYPE_BMP;  
                break;  
            case 13780:  
                $fileType = self::FILE_TYPE_PNG;  
                break;  
            default:  
                $fileType = self::FILE_TYPE_UNKNOWN;  
        }  
      
        //Fix  
        if ($strInfo['chars1']=='-1' AND $strInfo['chars2']=='-40' ) return self::FILE_TYPE_JPG;  
        if ($strInfo['chars1']=='-119' AND $strInfo['chars2']=='80' ) return self::FILE_TYPE_PNG;  
      
        return $fileType;  
    }

 };